package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.utils.ILock;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    /**
     * 进行秒杀优惠券功能
     * 基于mybatisplus层， 根据service层的 查询功能查询优惠券
     * 判断是否到售卖时间，是否结束
     * 如果售卖时间正常
     * 判断库存是否充足
     * 如果充足，获取下单的id，UserHolder
     * 判断是否买过
     * 如果，没有买过，下单，信息存入数据库（一人一单）,
     * 库存数量减一
     * redis:
     * 库存数量减一 increase （-1 ）
     * key:
     * SECKILL_STOCK_KEY + voucher.getId()
     */
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private RedissonClient redissonClient;

    private static  final  DefaultRedisScript<Long> SECKILL_SCRIPT; ;
    static {
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    private  static  final ExecutorService SECKILL_ORDER_EXECUTOR =
            Executors.newSingleThreadExecutor();

    //添加到阻塞队列以后，在postconstruct方法的init中，添加内部类
    @PostConstruct
    private  void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrederHandler());
    }

    private  class  VoucherOrederHandler implements Runnable{
     String queName = "stream.orders";
        @Override
        public void run() {
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queName, ReadOffset.lastConsumed())
                    );
                    if(list == null || list.isEmpty()){
                        continue;
                    }
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

//                    VoucherOrder voucherOrder = orderTasks.take();
                   //处理订单
                    handleVoucherOrder(voucherOrder);
                    stringRedisTemplate.opsForStream().acknowledge(
                            queName,"g1", entries.getId()
                    );
                } catch (Exception e) {
                    log.error("处理异常",e);

                }

            }
        }
        private void handlePendingList(){
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queName, ReadOffset.lastConsumed())
                    );
                    if(list == null || list.isEmpty()){
                        break;
                    }
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(
                            value, new VoucherOrder(), true);
                    createVoucherOrder(voucherOrder);
                    stringRedisTemplate.opsForStream().acknowledge(
                            queName,
                            "g1",
                            entries.getId()
                    );
                } catch (Exception e) {
                    log.error("处理异常",e);
                }
            }
        }
    }

    //怎么根据接口和实现类，获取代理对象：proxy
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
//    private   IVoucherOrderService proxy;

    @Override
    public Result seckillVoucher(Long voucherId) {
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        long  orderId = redisIdWorker.nextId("order");
        Long number = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        if(number != 0 ){
            return  Result.fail(number==1? "库存不足":"已经买过" );
        }
        //todo
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        orderTasks.add(voucherOrder);
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //根据id进行查询
        return Result.ok();
    }
    private void  handleVoucherOrder(VoucherOrder voucherOrder){
        //这个类用于拿到用户锁，再进行操作 redissonClient
        /*
            锁的作用：为了防止两个不同集群下的线程，经过前面的lua脚本，
            并判断用户未下单后，同时进入
           前面已经有过检验了， 但是只是为了保证
         */
        Long userId = voucherOrder.getUserId();
        RLock redisLock = redissonClient.getLock("lock:order" + userId);
        boolean b = redisLock.tryLock();
        if(!b){
            log.error("不允许重复下单！");
            return;
        }
        try {
            //注意：由于是spring的事务是放在threadLocal中，此时的是多线程，事务会失效
            createVoucherOrder(voucherOrder);
        } finally {
            // 释放锁
            redisLock.unlock();
        }
    }
    private void createVoucherOrder(VoucherOrder voucherOrder) {


        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();

            VoucherOrder one = query().eq("user_id", userId).eq("voucher_id", voucherId).one();
            if (one != null) {
                log.error("用户已经购买过了");
                return ;
            }

            //减少库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock -1 ")
                    .eq("voucher_id", voucherId)
                    .gt("stock", 0)
                    .update();

            if (!success) {
                log.error("用户已经购买过了");
                return;
            }

            save(voucherOrder);


    }

    }

//        @Override
//        public Result seckillVoucher(Long voucherId) {
//
//            SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//            LocalDateTime now1 = LocalDateTime.now();
//            if (voucher.getBeginTime().isAfter(now1)) {
//                return Result.fail("秒杀没开始");
//
//            }
//            if (voucher.getEndTime().isBefore(now1)) {
//                return Result.fail("秒杀结束");
//
//            }
//            String s = stringRedisTemplate.opsForValue().get(SECKILL_STOCK_KEY + voucherId);
//            if (s == null) {
//                return Result.fail("没有秒杀");
//            }
//            long count = Long.parseLong(s);
//            if (count <= 0) {
//                return Result.fail("券不够");
//            }
//            return createVoucherOrder(voucherId, voucher);
//        }

//
//    private Result createVoucherOrder(Long voucherId, SeckillVoucher voucher) {
//
//
//        Long userId = UserHolder.getUser().getId();
//        RLock lock = redissonClient.getLock("lock:order" + userId + ":" + voucherId);
//        boolean isLock = lock.tryLock();
//
//
//        if (!isLock) {
//            return Result.fail("不允许重复下单！");
//        }
//        try {
//            VoucherOrder one = query().eq("user_id", userId).eq("voucher_id", voucherId).one();
//            if (one != null) {
//                return Result.fail("已经购买过一次");
//            }
//
//            //减少库存
//            boolean success = seckillVoucherService.update()
//                    .setSql("stock=stock -1 ")
//                    .eq("voucher_id", voucherId)
//                    .gt("stock", 0)
//                    .update();
//            if (!success) {
//                return Result.fail("库存不足");
//            }
//            stringRedisTemplate.opsForValue().increment(SECKILL_STOCK_KEY + voucherId, -1);
//
//
//            //创建订单：
//            VoucherOrder voucherOrder = new VoucherOrder();
//            voucherOrder.setUserId(userId);
//            voucherOrder.setVoucherId(voucherId);
//            long orderId = redisIdWorker.nextId("order");
//            voucherOrder.setId(orderId);
//            save(voucherOrder);
//
//            return Result.ok(orderId);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        } finally {
//            lock.unlock();
//        }
//
//    }
//    }
//    private Result createVoucherOrder(Long voucherId, SeckillVoucher voucher) {
//        //55555555555555
//
//        Long userId = UserHolder.getUser().getId();
//        //
//        SimpleRedisLock redisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//
//        boolean isLock = redisLock.tryLock(1200);
//
//        if (!isLock) {
//            return Result.fail("不允许重复下单！");
//        }
//        try {
//            VoucherOrder one = query().eq("user_id", userId).eq("voucher_id", voucherId).one();
//            if (one != null) {
//                return Result.fail("已经购买过一次");
//            }
//
//            //减少库存
//            boolean success = seckillVoucherService.update()
//                    .setSql("stock=stock -1 ")
//                    .eq("voucher_id", voucherId)
//                    .gt("stock", 0)
//                    .update();
//            if (!success) {
//                return  Result.fail("库存不足");
//            }
//            stringRedisTemplate.opsForValue().increment(SECKILL_STOCK_KEY + voucherId, -1);
//
//
//            //创建订单：
//            VoucherOrder voucherOrder = new VoucherOrder();
//            voucherOrder.setUserId(userId);
//            voucherOrder.setVoucherId(voucherId);
//            long orderId = redisIdWorker.nextId("order");
//            voucherOrder.setId(orderId);
//            save(voucherOrder);
//
//            return Result.ok(orderId);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        } finally {
//            redisLock.unlock();
//        }
//    }




